package com.xbb.util;

import com.xbb.bean.Sidebar;
import com.xbb.controller.SideController;
import com.xbb.dao.SidebarMapperDao;
import org.omg.PortableInterceptor.Interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xbb on 15/7/9.
 */

public class MyInterceptor  implements HandlerInterceptor{

    @Resource
    private SidebarMapperDao dao;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        if(session.getAttribute("username") != null){
            return true;
        }else{
            httpServletResponse.sendRedirect("../toLogin.do");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        String requestUri=httpServletRequest.getServletPath();
        //给controller做统一的处理----加菜单
        List<Sidebar> menuList=dao.findParent();
        for(Sidebar s : menuList){
            s.setRequestUri(requestUri);
            List<Sidebar> sidebars=dao.findChild(s.getId());
            for(Sidebar ss:sidebars){
                ss.setRequestUri(requestUri);
            }
            if(sidebars!=null){
                s.setSubMenu(sidebars);
            }
        }
        httpServletRequest.setAttribute("menuList",menuList);

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
